def binary_search(arr, target):
    """
    二分查找：有序数组中不断缩小范围查找，时间复杂度O(log n)
    arr：有序数组
    target：待查找元素
    """
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

# 测试
arr = [1, 2, 3, 4, 5, 6, 9]
print(binary_search(arr, 5))  # 输出：4
print(binary_search(arr, 7))  # 输出：-1